package com.market.member.service.impl;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.MemberAuthConfigInfo;
import com.block.db.entity.MemberAuthInfo;
import com.block.db.entity.MemberAuthRecordInfo;
import com.block.db.entity.MemberBaseInfo;
import com.block.db.mapper.MemberAuthInfoMapper;
import com.block.db.mapper.MemberAuthRecordInfoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.market.member.enums.AuthStatusEnum;
import com.market.member.enums.AuthTypeEnum;
import com.market.member.factory.AuthPlatformFactory;
import com.market.member.model.dto.AuthHandleDTO;
import com.market.member.model.dto.AuthQueryDTO;
import com.market.member.model.result.AuthHandleResult;
import com.market.member.model.result.AuthQueryResult;
import com.market.member.service.IMemberAuthConfigInfoService;
import com.market.member.service.IMemberAuthRecordInfoService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户认证历史 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-09
 */
@Service
public class MemberAuthRecordInfoServiceImpl extends ServiceImpl<MemberAuthRecordInfoMapper, MemberAuthRecordInfo> implements IMemberAuthRecordInfoService {

    private static final Logger log = LogFactory.getCommLog();

    @Resource
    MemberAuthInfoMapper memberAuthInfoMapper;
    @Resource
    MemberBaseInfoMapper memberBaseInfoMapper;
    @Autowired
    IMemberAuthConfigInfoService memberAuthConfigInfoService;

    @Override
    @Transactional
    public ResponseVo handleAuthInfo(Long uid) {

        try {

            MemberAuthInfo memberAuthInfo = memberAuthInfoMapper.getEntityInfoByUid(uid);
            MemberBaseInfo memberBaseInfo = memberBaseInfoMapper.getMemberInfoByUidLock(uid);
            /**
             *
             */
            MemberAuthRecordInfo newEntity = new MemberAuthRecordInfo();
            newEntity.setUid(uid);
            newEntity.setType(AuthTypeEnum.AUTH.getValue());
            newEntity.setPlatform("ALI");
            newEntity.setStatus(AuthStatusEnum.INIT.getValue());
            boolean saveRes = this.save(newEntity);

            MemberAuthConfigInfo authConfigInfo = memberAuthConfigInfoService.getById("1");

            AuthHandleDTO authHandleDTO = new AuthHandleDTO();

            AuthHandleResult authRecordResult = AuthPlatformFactory.getService(authConfigInfo.getPlatform()).handleAuthInfo(authConfigInfo, authHandleDTO);
            log.info("【实名认证】实名认证结果【authRecordResult】{}", JSON.toJSONString(authRecordResult));

            MemberAuthRecordInfo updateEntity = new MemberAuthRecordInfo();
            updateEntity.setId(newEntity.getId());
            updateEntity.setParamInfo(authRecordResult.getParamInfo());
            updateEntity.setStatus(authRecordResult.getAuthStatus());
            updateEntity.setCode(authRecordResult.getCode());
            updateEntity.setMessage(authRecordResult.getMessage());
            updateEntity.setResultInfo(authRecordResult.getResultInfo());
            this.updateById(updateEntity);

            if (!StrUtil.equals(authRecordResult.getAuthStatus(), AuthStatusEnum.SUCCESS.getValue())){
                // 实名成功，更新认证信息，
                return new ResponseVo(AppRspCodeConstant.ACTION_ERROR, "实名认证失败，请重试");
            }

            // 更新实名认证结果
            MemberAuthInfo updateAuthInfo = new MemberAuthInfo();
            updateAuthInfo.setUid(uid);
            updateAuthInfo.setAuthStatus(AuthStatusEnum.SUCCESS.getValue());
            updateAuthInfo.setAuthRecordId(newEntity.getId());
            int i = memberAuthInfoMapper.updateById(updateAuthInfo);

            MemberBaseInfo updateBaseInfo = new MemberBaseInfo();
            updateBaseInfo.setUid(uid);
            updateBaseInfo.setRealname(memberAuthInfo.getRealname());
            updateBaseInfo.setAuthFlag(1);
            int i1 = memberBaseInfoMapper.updateById(updateBaseInfo);

            return new ResponseVo(AppRspCodeConstant.SUCCESS);
        }catch (Exception exception){
            // TODO: 2023/8/9 实名认证失败
            exception.printStackTrace();
        }
        return new ResponseVo(AppRspCodeConstant.ACTION_ERROR, "实名认证失败，请重试！");
    }

    @Override
    public MemberAuthRecordInfo saveRecordInfo(MemberAuthConfigInfo authConfigInfo, Long uid, String reqData) {
        MemberAuthRecordInfo memberAuthRecordInfo = new MemberAuthRecordInfo();
        memberAuthRecordInfo.setUid(uid);
        memberAuthRecordInfo.setRequestParam(reqData);
        memberAuthRecordInfo.setStatus(AuthStatusEnum.INIT.getValue());
        memberAuthRecordInfo.setConfigId(authConfigInfo.getId());
        memberAuthRecordInfo.setPlatform(authConfigInfo.getPlatform());

        boolean save = this.save(memberAuthRecordInfo);
        if (save){
            return this.getById(memberAuthRecordInfo.getId());
        }
        return null;
    }

    /**
     * 查询认证状态结果
     * @param orderNo
     * @return
     */
    @Override
    @Transactional
    public boolean queryAuthVerifyResult(String orderNo){
        MemberAuthRecordInfo authRecordInfo = this.baseMapper.getEntityByIdLock(orderNo);
        if (ObjectUtil.isEmpty(authRecordInfo)){
            return false;
        }
        if (!StrUtil.equals(authRecordInfo.getStatus(), AuthStatusEnum.WAITING.getValue())){
            // 没有成功，并且不是等于待查询状态
            return true;
        }

        AuthQueryDTO authQueryDTO = new AuthQueryDTO();
        authQueryDTO.setUid(authRecordInfo.getUid());
        authQueryDTO.setOrderNo(String.valueOf(authRecordInfo.getId()));
        authQueryDTO.setOutOrderNo(authRecordInfo.getOutOrderNo());
        /**
         * 待查询状态，需要进行查询
         */
        MemberAuthConfigInfo authConfigInfo = memberAuthConfigInfoService.getById(authRecordInfo.getConfigId());

        AuthQueryResult authQueryResult  = new AuthQueryResult();
        try {
            authQueryResult = AuthPlatformFactory.getService(authConfigInfo.getPlatform())
                    .queryAuthVerifyResult(authQueryDTO, authConfigInfo);
            log.info("【认证结果查询】查询结束【authQueryResult】{}【authQueryDTO】{}",
                    JSON.toJSONString(authQueryResult), JSON.toJSONString(authQueryDTO));
        }catch (Exception exception){
            exception.printStackTrace();
            // TODO: 2023/8/13
            authQueryResult.setSuccess(false);
        }

        if (!authQueryResult.isSuccess()){
            // TODO: 2023/8/13 消息通知
            return false;
        }

        // 更新结果
        MemberAuthRecordInfo updateEntity = new MemberAuthRecordInfo();
        updateEntity.setId(authRecordInfo.getId());
        updateEntity.setStatus(authQueryResult.getAuthStatus());
        updateEntity.setResultInfo(authQueryResult.getResultInfo());
        boolean updateRes = this.updateById(updateEntity);

        if (!updateRes){
            return false;
        }

        if (StrUtil.equals(authQueryResult.getAuthStatus(), AuthStatusEnum.SUCCESS.getValue())){
            MemberAuthInfo memberAuthInfo = memberAuthInfoMapper.getEntityInfoByUid(authRecordInfo.getUid());
            MemberBaseInfo memberBaseInfo = memberBaseInfoMapper.getMemberInfoByUidLock(authRecordInfo.getUid());
            if (StrUtil.equals(memberAuthInfo.getAuthStatus(), AuthStatusEnum.SUCCESS.getValue()) &&
                    ObjectUtil.equals(memberBaseInfo.getAuthFlag(), Integer.valueOf(1))){
                // 已经认证完成的，不再进行认证
                return true;
            }

            // 认证成功，更新用户认证信息
            MemberAuthInfo updateAuthInfo = new MemberAuthInfo();
            updateAuthInfo.setUid(authRecordInfo.getUid());
//            updateAuthInfo.setRealname(authQueryResult.getRealname());
//            updateAuthInfo.setIdcard(authQueryResult.getIdCard());
            updateAuthInfo.setAuthStatus(AuthStatusEnum.SUCCESS.getValue());
            updateAuthInfo.setFaceRecordId(authRecordInfo.getId());
//            updateAuthInfo.setFaceImg(authQueryResult.getIdCardFrontUrl());
//            updateAuthInfo.setNationImg(authQueryResult.getIdCardBackUrl());
            updateAuthInfo.setHeadImg(authQueryResult.getPersonImageUrl());
            updateAuthInfo.setFaceStatus(AuthStatusEnum.SUCCESS.getValue());
            int i1 = memberAuthInfoMapper.updateById(updateAuthInfo);
            if (i1<1){
                return false;
            }

            MemberBaseInfo updateBaseInfo = new MemberBaseInfo();
            updateBaseInfo.setUid(authRecordInfo.getUid());
            updateBaseInfo.setUsername(DesensitizedUtil.chineseName(memberAuthInfo.getRealname()));
            updateBaseInfo.setRealname(memberAuthInfo.getRealname());
            updateBaseInfo.setFaceFlag(Integer.valueOf(1));
            updateBaseInfo.setAuthFlag(Integer.valueOf(1));
            int i = memberBaseInfoMapper.updateById(updateBaseInfo);
            return i > 0;
        }
        return false;
    }
}

